package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import dao.BaseDao;
import dao.BranchesDao;
import entity.Branches;
import entity.CityArea;

public class BranchesDao_impl extends BaseDao implements BranchesDao{

	Connection conn = null;
	ResultSet set = null;
	PreparedStatement tmt = null;
	@Override
	public List<Branches> select() {
		List<Branches> l = new ArrayList<Branches>();
		try {
			String sql = "select a.*,b.name as namea from Branches as a,CityArea as b where a.cityAreald=b.id ";
			conn = getConnection();
		 tmt = conn.prepareStatement(sql);
		set = 	tmt.executeQuery();
		while(set.next())
		{
			Branches a= new Branches();
			CityArea b =new CityArea();
			a.setName(set.getString("name"));
			a.setTelephone(set.getString("telephone"));
			a.setAddress(set.getString("address"));
		    a.setId(set.getInt("id"));
		    a.setCityAreald(set.getInt("CityAreald"));
		    b.setName(set.getString("namea"));
		    a.setCityArea(b);
		    l.add(a);
		    
		
		}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return l;
	}

	@Override
	public int update(Branches a) {
		int num = 0 ;
		try {
			conn = getConnection();
			String sql = "update Branches set name=?,address=?,telephone=?,cityAreald=? where id=?";
		tmt = 	conn.prepareStatement(sql);
		tmt.setString(1, a.getName());
		tmt.setString(2, a.getAddress());
		tmt.setString(3, a.getTelephone());
		tmt.setInt(4, a.getCityAreald());
		tmt.setInt(5, a.getId());
		 num = tmt.executeUpdate();
		} catch (Exception e) {
		e.printStackTrace();
		}
		
		return num ;
	}

	@Override
	public List<Branches> select1(int a) {
		List<Branches> l = new ArrayList<Branches>();
		try {
			String sql = "select a.*,b.name as namea,b.id as ids from Branches as a,CityArea as b where a.cityAreald=b.id and a.id=? ";
			conn = getConnection();
		 tmt = conn.prepareStatement(sql);
		 tmt.setInt(1, a);
		set = 	tmt.executeQuery();
		while(set.next())
		{
			Branches c= new Branches();
			CityArea b =new CityArea();
			c.setName(set.getString("name"));
			c.setTelephone(set.getString("telephone"));
			c.setAddress(set.getString("address"));
		    c.setId(set.getInt("id"));
		    c.setCityAreald(set.getInt("CityAreald"));
		    b.setName(set.getString("namea"));
		    b.setId(set.getInt("ids"));
		    c.setCityArea(b);
		    l.add(c);
		    
		
		}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return l;
	}

}
